import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
import 'rxjs/Rx';

@Injectable ()
export class WebSocketService {

    WS : WebSocket;

    constructor () {
    }

    createObservableSocket ( url : string, id : number ) : Observable<any> {
        this.WS = new WebSocket (url);
        return new Observable<string> (
            observable => {
                this.WS.onmessage = ( event ) => observable.next (event.data);
                this.WS.onerror = ( event ) => observable.error (event);
                this.WS.onclose = ( event ) => observable.complete ();
                this.WS.onopen = ( event ) => this.sendMessage ({ productId : id });

                return () => this.WS.close()
            }
        ).map (message => JSON.parse (message));
    }

    sendMessage ( message : any ) {
        this.WS.send (JSON.stringify (message));
    }

}
